<!--送货单导入-->
<template>
  <div class="m-view-deliveryImport m-window">
    <div class="m-condition" v-loading="loading" v-if="!componentShow">
      <el-row>
        <el-col :span="12">
          <label>文件路径:</label>
          <el-input v-model="filePath" disabled></el-input>
          <el-button type="primary" @click="importFile">
            选择文件
            <input
              type="file"
              style="display:none"
              ref="importFile"
              accept=".xls, .xlsx"
              @change="onchange"
            >
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <a :href="tempUrl" class="m-tips" download="送货单导入模板.xlsx">导入前请点击下载---《送货单导入模板送货单导入模板》进行填写</a>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" class="m-buttonCol">
          <el-button @click="cancelImport">取消</el-button>
          <el-button type="primary" @click="comfirmImport">确认</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 订单导入详情 -->
    <div class="m-window" v-if="componentShow">
      <deliveryComponents
        @cancelComponents="cancelComponents"
        :getClickValue="getClickValue"
        :pageLayOut="pageLayOut"
        :deliveryState="deliveryState"
        :supplierInfo="supplierInfo"
        :companyInfo="companyInfo"
        :barCodes="barCodes"
      ></deliveryComponents>
    </div>
  </div>
</template>

<script>
import _Api from "@/api";
import XLSX from 'xlsx';
import deliveryComponents from "@/views/myLogistics/deliveryComponents";
import supplierInfo from "@/public/supplierInfo";
import Msg from "@/public/message";
import fileStream from "@/public/fileStream"

export default {
  data () {
    return {
      filePath: '',
      moduleName: '',
      componentShow: false,
      deliveryState: "import",
      pageLayOut: 'add',
      supplierInfo: [],
      companyInfo: {},
      purOrdNos: [],
      params: {},
      deliveryInfo: [],//导入的采购订单主信息
      getClickValue: '',//送货单明细
      loading: false,
      barCodes: [],
      tempUrl:''
    };
  },
  props: {
    removeTab: {
      type: Function
    },
    addTab: {
      type: Function
    }
  },
  beforeMount () {
  },
  mounted () {
    let that = this
    // authInfo.getAuthInfo().then((authCompanyInfo) => {
    //   that.comOptions = authCompanyInfo;
    // });
    // serviceTime.getServiceTime().then((serviceTime) => {
    //   that.beginDate = new Date((serviceTime.getTime() - 604800000)).Format("yyyy-MM-dd");
    //   that.endDate = serviceTime.Format("yyyy-MM-dd");
    // });
    this.getContractTemp()
    if (this.$global.user.userTypeId == "4") {
      //				var arrayList = [];
      //				arrayList.push(this.$global.supplierData);
      this.supplierInfo.push(this.$global.supplierData);
      if (this.supplierInfo[0] == null) {
        supplierInfo.getUserInfo(this.$global.user.userName).then((supplierInfo) => {
          that.supplierInfo = supplierInfo;
        })
      }
    }
  },
  components: {
    deliveryComponents
  },
  methods: {
    // 选择文件
    importFile () {
      this.$refs["importFile"].click()
    },
    // 子组件自定义事件回调
    cancelComponents (msg) {
      if (msg) {
        this.filePath = ""
        this.barCodes = []
        this.componentShow = false;
        this.btnShow = true;
      } else {
        let list = {
          cName: "送货单列表",
          name: "deliveryList",
          completed: true
        }
        this.addTab(list)
        this.filePath = ""
        this.componentShow = false;
        this.btnShow = true;
      }
    },
    // 确认导入
    comfirmImport () {
      this.params = {
        purOrdNo: this.purOrdNos[0],
        tblPurchaseordermxs: this.deliveryInfo
      }
      if (!this.filePath) {
        Msg.showPopMsg("请先选择订单模板填写再进行导入！");
        return
      } else if (this.purOrdNos.length > 1) {
        Msg.showPopMsg("每次只能导入一个采购订单明细");
        return
      }
      this.getDeliveryDetail(this.params)
    },
    // 取消导入关闭页面
    cancelImport () {
      this.removeTab()
    },
    // 文件选择回调
    onchange (evt) {
      this.deliveryInfo = []
      this.purOrdNos = []
      let files = evt.target.files;
      if (!files || files.length == 0) return;
      //          let that = this;
      let excelFile = files[0];
      this.filePath = excelFile.path
      let fileType = excelFile.name.substring(excelFile.name.lastIndexOf('.') + 1);
      if (fileType != "" && fileType != null) {
        if (fileType != "xls" && fileType != "xlsx") {
          this.$message({
            message: '请上传Excel文件！',
            type: 'warning'
          });
          let elementId = document.getElementById("importFile");
          elementId.value = '';
          return false;
        }
      } else {
        this.$message({
          message: '请上传Excel文件！',
          type: 'warning'
        });
        let elementId = document.getElementById("importFile");
        elementId.value = '';
        return false;
      }
      const size = excelFile.size / 1024 / 1024 < 20;
      if (!size) {
        this.$message({
          message: '上传模板大小不能超过 20MB!',
          type: 'warning'
        });
        let elementId = document.getElementById("importFile");
        elementId.value = '';
        return false;
      }
      let reader = new FileReader();
      reader.onload = (e) => {
        // 数据预处理
        this.loading = true;
        let binary = "";
        let bytes = new Uint8Array(e.target.result);
        let length = bytes.byteLength;
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        /* 读取 workbook */
        let wb = XLSX.read(binary, {
          type: 'binary'
        });
        /* 选择第一个sheet */
        let wsname1 = wb.SheetNames[0];
        let ws1 = wb.Sheets[wsname1];
        let wsname2 = wb.SheetNames[1];
        let ws2 = wb.Sheets[wsname2];
        /* excel转换json数组,加上{header:1}是普通数组，不写是对象数组 */
        let json = XLSX.utils.sheet_to_json(ws1);
        let json1 = XLSX.utils.sheet_to_json(ws2);
        if (json.length > 100 || json1.length > 100) {
          this.$message({
            message: '上传的条数不能大于100条!',
            type: 'warning'
          });
          let elementId = document.getElementById("importFile");
          elementId.value = '';
          this.loading = false;
          return false;
        }
        if (json.length === 0) {
          this.$message({
            message: '该EXCEL没有合适数据！',
            type: 'warning'
          });
          let elementId = document.getElementById("importFile");
          elementId.value = '';
          this.loading = false;
          return false;
        }
        this.loading = false;
        let config = {
          // "价格单位": "priceUnit",
          // "价格数量": "priceAmount",
          // "单位": "unitCode",
          "行号": "purOrdMxNo",
          "送货数量": "actualAmount",
          "采购订单号": "purOrdNo"
        }
        json.forEach((item, index) => {
          if (item.hasOwnProperty("采购订单号")) {
            let obj = {}
            // this.params = {
            //   purOrdNo: item["采购订单号"]
            // }
            let keys = Object.keys(config)
            keys.forEach((k, i) => {
              let values = Object.values(config)
              let key = values[i]
              if (key == "purOrdMxNo") item[k] = Number(item[k])
              obj[key] = item[k]
            })
            this.deliveryInfo.push(obj)
            this.purOrdNos.push(item["采购订单号"])
          } else {
            Msg.showErrorMsg("上传格式错误，请先下载模板进行填写！");
          }
        })
        // let obj = {};
        // for (let a in json) {
        // 	for (let key in config) {
        // 		if (JSON.stringify(config[key]) != "{}") {
        // 			if (json[a].hasOwnProperty(Object.keys(config[key]).toString())) {
        // 				let k = Object.values(config[key]).toString();//object Key值
        // 				let v = json[a][Object.keys(config[key]).toString()];//object Value值
        //         this.params[k] = v;
        //         break
        // 			} else {
        //         Msg.showErrorMsg("上传格式错误，请先下载模板进行填写！");
        //       }
        // 		}
        // 	}
        // 	// if (JSON.stringify(obj) != "{}")
        // 	// 	arr.push(obj);
        // }
        if (json1.length > 0) {
          //  let config1 = [{"条码":"barCode"},{"行号":"purOrdMxNo"}];
          //   let obj = {};
          json1.forEach(item => {
            this.barCodes.push({
              barCode: item['条码'],
              purOrdMxNo: item['行号']
            })
          })
        }
      }
      reader.readAsArrayBuffer(excelFile);
    },
    // 根据订单号查询送货单订单详情
    getDeliveryDetail (params) {
      let that = this
      that.loading = true
      this.getClickValue = []
      _Api.importQueryOrder(params).then(function (response) {
        that.loading = false;
        let data = response.data;
        if (data.code == "1") {
          const { tblPurchaseorderbill: { address, companyCode, companyName } } = data.rows
          that.getClickValue = data.rows.tblPurchaseordermx
          if (that.barCodes.length > 0) {
            that.getClickValue.forEach((val) => {
              that.$set(val, "barcodes", [])
              that.barCodes.forEach(code => {
                if (code.purOrdMxNo == val.purOrdMxNo) {
                  val.barcodes.push(code.barCode)
                }
              })
            });
          }
          if (that.deliveryInfo.length > 0) {
            let arr = []
            that.deliveryInfo.forEach(code => {
              that.getClickValue.forEach((val) => {
                if (code.purOrdMxNo == val.purOrdMxNo) {
                  // val.priceUnit = code.priceUnit
                  // val.priceAmount = code.priceAmount
                  // val.unitCode = code.unitCode
                  val.purOrdMxNo = Number(code.purOrdMxNo)
                  val.actualAmount = code.actualAmount
                  val.purOrdNo = code.purOrdNo
                  arr.push(val)
                }
              })
            });
            that.getClickValue = arr
          }
          that.companyInfo = {
            address,
            companyCode,
            companyName
          }
          that.componentShow = true
        } else {
          Msg.showErrorMsg(data.info);
        }
      })
        .catch((err) => {
          Msg.showErrorMsg(err.message);
        })
    },
     getContractTemp () {
    //  let  fileInfo = await fileStream.getFileInfo("contract").then(data => data).catch(err => {Msg.showErrorMsg(err)})
    //  let  stream = await fileStream.downLoadFile(fileInfo).then(data => data).catch(err => {Msg.showErrorMsg(err)})
     fileStream.getPrintTempUrl("deliveryImport").then(url => {
         this.tempUrl = url
     })
    }
  }
};
</script>

<style>
</style>